<template>
  <div class="container">
    <DataList
      ref="dataList"
      :propAutoFetchData="false"
      :propNoCheck="true"
      :propSearchFields="['code']"
      :propSearchTextAppend="'采购单号'"
      propUrl="/order/purchase_orders/pageCommon"
      showFieldPk="id"
      :showFieldList="cpShowFieldList"
      :showDataFmtFun="showDataFmtFun"
      :vanFieldLabelWith5="true"
      @click="itemClick"
      @afterLoad="afterLoad"
      :sortDefault="{field: 'gmtCreate',type: 'desc'}"
    >
    </DataList>

    <!--品类选择-->
    <customDrawer  title="订单详情" ref="customDrawerOrder" :autoHide="false" p94Only placement="right" :footer="null">
      <template #content>
        <customSpace fullWidth style="top: 33px;padding: 5px 0px; position: fixed; top: 33px;  z-index: 999;
    background: #fff;"  v-if="!isReadonly && form.status == 2">
          <template #content>
            <customButton  title="确认订单" theme="primary" size="medium" @click="handleOrder('orderConfirm', '确认订单,将生成相关送货单')"/>
            <customButton  title="关闭订单"  theme="danger" size="medium" @click="handleOrder('orderClose','关闭订单')"/>
          </template>
        </customSpace>

        <div id="box-base" class="box-title" :style="{marginTop: !isReadonly && form.status == 2 ? '31px': '0px'}">订单信息</div>
        <customForm :data="form"   ref="editForm" :disabled="true" layoutMini >
          <template #content>
            <customFormItem
              v-for="item in cpFormFieldList"  :key="item.name"
              :parent="_self" :form="form"
              :label="item.label" :name="item.name"  :type="item.queryType"
              :config="item.queryConfig"
              :full-width="24 == item.span"
            />
          </template>
        </customForm>

        <div id="box-dtl" class="box-title">订单明细</div>
        <DataList
          ref="dataListDtl"
          :propAutoFetchData="false"
          :propNoCheck="true"
          :propSearchFields="['materialName','materialSpec']"
          :propSearchTextAppend="'品名、品规'"
          propUrl="/order/purchase_order_items/pageCommon"
          showFieldPk="id"
          :showFieldList="cpDtlshowFieldList"
          :vanFieldLabelWith5="true"
          :sortDefault="{field: 'gmtCreate',type: 'desc'}"
        >
        </DataList>
      </template>
    </customDrawer>
  </div>
</template>

<script>
export default {
  help: '采购订单-列表',
  props:['statusEq', 'readonly'],
  data() {
    return {
      poCode: '',
      activeNames: ['1'],
      form: {},
      submitPopShow: false,
    }
  },
  computed: {
    isReadonly() {
      return true == this.readonly
    },

    // 表单字段
    cpFormFieldList() {
      return this.cpShowFieldList.filter(item1 => !item1.showFormOpenDisabled)
    },

    // 主单据显示字段
    cpShowFieldList() {
      let fieldList = [
        {label:'采购单号',name:'code',span:24, isTitle: true},
        {
          label:'订单状态',name:'status',span:12,isTitleSub: true,
          queryType: this.constCommon.formItemType.selectDict.name,
          queryConfig: {
            dictType: this.constCommon.dictType.orderPoStatus,
            multiple: true
          },
          filterDisabled: this.strings.isNotBlank(this.statusEq),sortDisabled: this.strings.isNotBlank(this.statusEq)
        },
        {
          label:'来源',name:'fromType',span:12,isTitleSub: true,filterDisabled: true,sortDisabled: true,showFormOpenDisabled: true,

          fmtFun: (value, row) => {
            if ('SCP' == value) {
              return `<span style="background-color: #0042b2; color: #fff;padding: 3px;font-size: 10px;margin-left: 3PX;">SCP</span>`
            }
            return `<span style="background-color: #1aad6d; color: #fff;padding: 3px;font-size: 10px;margin-left: 3PX;">LMS</span>`
          }
        },
        {
          label:'确认状态',name:'supplierConfirmStatus',span:12,
          queryType: this.constCommon.formItemType.selectDict.name,
          queryConfig: {
            dictType: this.constCommon.dictType.orderPoSupplierConfirmStatus,
            multiple: true
          },
        },
        {
          label:'已关闭',name:'isClosed',span:12,flagBoolean: true,
          queryType: this.constCommon.formItemType.switch.name,
          queryConfig: {
            dictType: this.constCommon.dictType.commonYesNo,
          },
        },
        {label:'需求时间',name:'purchaseDate',span:12,queryType: this.constCommon.formItemType.datePickerBetween.name},
        {label:'订单金额',name:'totalAmount',span:12,filterDisabled: true,sortDisabled: true},
        {label:'审核人',name:'auditorName',span:12,showFormDtlDisabled: true,filterDisabled: true,sortDisabled: true},
        {label:'收货仓库',name:'warehouseName',span:24,showFormDtlDisabled: true,filterDisabled: true,sortDisabled: true},
        {
          label: '审核时间',
          name: 'gmtAudited',
          span: 24,
          queryType: this.constCommon.formItemType.datePickerBetween.name,
          queryConfig: {
            format: this.dates.defaultDateTimePattern
          },showFormDtlDisabled: true

        },
        {
          label: '创建时间',
          name: 'gmtCreate',
          span: 24,
          queryType: this.constCommon.formItemType.datePickerBetween.name,
          queryConfig: {
            format: this.dates.defaultDateTimePattern
          }
        },
        {
          label:'关闭原因',name:'closedReason',span:24,filterDisabled: true,sortDisabled: true,showFormDtlDisabled: true
        },
        {
          label:'备注',name:'remark',span:24,filterDisabled: true,sortDisabled: true,showFormDtlDisabled: true
        }
      ]
      fieldList = [...fieldList, ...this.constCommon.filterCommon.spAndHp()]
      return fieldList
    },

    // 明细字段
    cpDtlshowFieldList() {
      let fieldList = [
        {label:'品名',name:'materialName',span:12, isTitle: true},
        {label:'品规',name:'materialSpec',span:24},
        {label:'发货状态',name:'deliveryStatus',span:24,
          queryType: this.constCommon.formItemType.selectDict.name,
          queryConfig: {
            dictType: this.constCommon.dictType.orderPoDeliveryStatus,
            multiple: true
          },
          isTitleSub: true,
        },
        {label:'订单数量',name:'qty',span:12,filterDisabled: true,sortDisabled: true},
        {label:'发货数量',name:'deliveredQty',span:12,filterDisabled: true,sortDisabled: true},
        {label:'单位',name:'unit',span:12,filterDisabled: true,sortDisabled: true},
        {label:'单价',name:'price',span:12,filterDisabled: true,sortDisabled: true},
        {label:'生产厂商',name:'manufacturerName',span:24},
        {label:'注册证号',name:'certificateNo',span:24},
        {label:'备注',name:'remark',span:24,sortDisabled: true},
        {label:'创建时间',name:'gmtCreate',span:24,queryType: this.constCommon.formItemType.datePicker.name,filterDisabled: true,},
      ]
      return fieldList
    }
  },
  mounted() {
    this.loadOrder()
  },
  methods: {
    loadOrder() {
      let wrapper = this.$newWrapper()
      if (this.statusEq) {
        wrapper.eq('status', this.statusEq)
      }
      this.$refs.dataList.setQueryWrapper(wrapper)
    },
    showDataFmtFun(data) {
      data.forEach(item => {
        item.purchaseDate = this.dates.formatToAnotherPattern(item.purchaseDate)
      })
      return data
    },
    itemClick(item) {
      this.form = item

      let wrapper = this.$newWrapper()
      wrapper.eq('poId', this.form.id)
      this.$refs.dataListDtl.setQueryWrapper(wrapper)
      this.$refs.customDrawerOrder.show()
    },

    // 订单操作
    handleOrder(fun, title) {
      this.utilMessage.confirm(`是否${title}`, () => {
        this[fun]()
      })
    },

    // 确认订单
    orderConfirm() {
      this.utilVue.loadShow(true)
      this.$ajax.post(`/order/purchase_orders/able/${this.form.id}`).then((response) => {
        this.utilVue.loadHide()
        if (response.code == 0) {
          this.$refs.customDrawerOrder.hide()
          this.utilMessage.success(response.msg)
          this.loadOrder()
        }
      })
    },

    // 关闭订单
    orderClose() {
      this.utilMessage.confirmInput('请输入关闭原因', (closeReason) => {
        this.utilVue.loadShow(true)
        this.$ajax.post(`/order/purchase_orders/disable`, {
          id: this.form.id,
          reason: closeReason
        }).then((response) => {
          this.utilVue.loadHide()
          if (response.code == 0) {
            this.$refs.customDrawerOrder.hide()
            this.utilMessage.success(response.msg)
            this.loadOrder()
          }
        })
      })
    },

    // 订单数据加载完
    afterLoad(data) {
      if (this.poCode) {
        if (!data || data.length ==0) {
          this.utilMessage.warning(`未找到符合条件的采购订单[${this.poCode}]`)
          return
        }
        if (data[0].code != this.poCode) {
          return
        }
        this.poCode = ''
        this.itemClick(data[0])
      }
    },
  },
  watch: {
    '$route.meta.poCode': {
      immediate: true,
      handler(newVal) {
        if (!newVal) {
          return
        }

        this.$nextTick(() => {
          this.poCode = newVal
          delete this.$route.meta.poCode
          const wrapper = this.$newWrapper().eq('code', this.poCode)
          this.$refs.dataList.setQueryWrapper(wrapper)
        })
      }
    }
  }
}
</script>
